/*
 *  JVending - JSP Tag Library
 *  Copyright (C) 2004  Shane Isbell
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.jvending.provisioning.taglib;

import org.jvending.provisioning.deliverable.BaseDeliverable;
import org.jvending.provisioning.deliverable.BaseDescriptorFile;

import javax.provisioning.BundleDescriptor;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.net.URI;
import java.util.logging.Logger;

/**
 * @author Shane Isbell
 * @since 1.3.9a
 */

public class ContentReferenceTag extends TagSupport {

    private static Logger logger = Logger.getLogger("ContentReferenceTag");

    private BundleDescriptor bundleDescriptor;

    //TO DO: Add displayName as parameter

    private String wapEnabled = "false";

    private String emulatorEnabled = "false";

    public void setWapEnabled(String wapEnabled) {
        this.wapEnabled = wapEnabled;
    }

    public String getWapEnabled() {
        return wapEnabled;
    }


    public String getEmulatorEnabled() {
        return emulatorEnabled;
    }

    public void setEmulatorEnabled(String emulatorEnabled) {
        this.emulatorEnabled = emulatorEnabled;
    }

    public int doStartTag() throws JspTagException {
        bundleDescriptor = (BundleDescriptor)
             pageContext.getAttribute("descriptor", 
                                       pageContext.PAGE_SCOPE);
        return SKIP_BODY;
    }

    public int doEndTag() throws JspTagException {
        if(emulatorEnabled.equalsIgnoreCase("true"))
            return doEndTagForEmulator();
        else 
            return doEndTagForDevice();
    }

    public int doEndTagForDevice() throws JspTagException {
        if(bundleDescriptor == null) return EVAL_PAGE;

        try {
          BaseDeliverable contentFile = (BaseDeliverable) bundleDescriptor.getContentFile();
          BaseDescriptorFile descriptorFile = (BaseDescriptorFile) bundleDescriptor.getDescriptorFile();
          String ref = null;
          if(contentFile != null) {
              URI uri = contentFile.getURI();
              if(!isRemoteUri(uri.toString()))
                  ref = "/jvending/adapter?bundleId=" + bundleDescriptor.getBundleID();
              else
                  ref = uri.toString();
          } else if(descriptorFile != null) {
              URI uri = descriptorFile.getURI();
              if(!isRemoteUri(uri.toString()))
                  ref = "/jvending/adapter?bundleId=" + bundleDescriptor.getBundleID();
              else
                  ref = uri.toString();
          } else {//sanity check
              logger.warning("This content has no descriptor and no content!!!");
          }

          if(wapEnabled.equals("true")) {
              ref = ref.replaceAll("[&]", "&amp;"); 
          }
          pageContext.getOut().println("<a href = \"" + ref + "\">"  + bundleDescriptor.getDisplayName(null) + "</a>");
        } catch(IOException e) {
            e.printStackTrace();
            throw new JspTagException("Could not End Tag");
        } 
        return EVAL_PAGE;
    }

/*
 * Need to add emulator enabled tag due to bug in Sun's wireless toolkit 2.2. For some reason,
 * it treats "/jvending/adapter" reference as "/jvending//jvending/adapter" which cause a 404.
 * Verify whether we can remove this method in later versions of the toolkit.
 */

    public int doEndTagForEmulator() throws JspTagException {
        if(bundleDescriptor == null) return EVAL_PAGE;

        try {
          BaseDeliverable contentFile = (BaseDeliverable) bundleDescriptor.getContentFile();
          BaseDescriptorFile descriptorFile = (BaseDescriptorFile) bundleDescriptor.getDescriptorFile();
          String ref = null;
          if(contentFile != null) {
              URI uri = contentFile.getURI();
              if(!isRemoteUri(uri.toString()))
                  ref = "/adapter?bundleId=" + bundleDescriptor.getBundleID();
              else
                  ref = uri.toString();
          } else if(descriptorFile != null) {
              URI uri = descriptorFile.getURI();
              if(!isRemoteUri(uri.toString()))
                  ref = "/adapter?bundleId=" + bundleDescriptor.getBundleID();
              else
                  ref = uri.toString();
          } else {//sanity check
              logger.warning("This content has no descriptor and no content!!!");
          }

          if(wapEnabled.equals("true")) {
              ref = ref.replaceAll("[&]", "&amp;"); 
          }
          pageContext.getOut().println("<a href = \"" + ref + "&ext=.jad\">" + bundleDescriptor.getDisplayName(null) + "</a>");
        } catch(IOException e) {
            e.printStackTrace();
            throw new JspTagException("Could not End Tag");
        } 
        return EVAL_PAGE;
    }

    private boolean isRemoteUri(String uri) {
        return (uri != null && (uri.startsWith("http://") || uri.startsWith("ftp://") || uri.startsWith("https://")));
    }

}